package org.metasketch.diagram.javafx.graphics;

import org.metasketch.editor.links.LineEnd;
import org.metasketch.editor.links.LineSection;
import org.metasketch.editor.links.LinkEnd;
import org.metasketch.editor.links.LinkEndType;

public class LinkEndBuilder {

	public static void buildEnds(DefaultLink link) {

		if (link.getLinkConfig() == null)
			return;

		buildEnd(link, link.getFirstSection(), link.getLinkConfig().getSource()
				.getLinkEnd(), true);

		buildEnd(link, link.getLastSection(), link.getLinkConfig().getTarget()
				.getLinkEnd(), false);

	}

	public static void buildEnd(DefaultLink link, LineSection section,
			LinkEnd linkEnd, boolean source) {

		buildEnd(link, section, linkEnd.getGraphic(), source);

	}

	public static void buildEnd(DefaultLink link, LineSection section,
			LinkEndType endType, boolean source) {

		if (source) {
			LineEnd end = getEndNode(endType);
			if (end != null) {
				end.setNewPosition((int) section.getStartX(),
						(int) section.getStartY(), (int) section.getEndX(),
						(int) section.getEndY());
				link.getChildren().add(end);
				section.setSourceLineEnd(end);
			}
		} else {
			LineEnd end = getEndNode(endType);
			if (end != null) {
				end.setNewPosition((int) section.getEndX(),
						(int) section.getEndY(), (int) section.getStartX(),
						(int) section.getStartY());
				link.getChildren().add(end);
				section.setTargetLineEnd(end);
			}
		}

	}

	public static LineEnd getEndNode(LinkEndType endType) {
		if (endType == LinkEndType.SQUARE
				|| endType == LinkEndType.FILLEDSQUARE) {
			return new SquareEndType(endType);
		} else if (endType == LinkEndType.CIRCLE
				|| endType == LinkEndType.FILLEDCIRCLE) {

			return new CircleEndType(endType);
		} else if (endType == LinkEndType.TRIANGLE
				|| endType == LinkEndType.FILLEDTRIANGLE) {

			return new TriangleEndType(endType);
		} else if (endType == LinkEndType.ARROW) {
			return new ArrowEndType(endType);
		}
		return null;

	}
}
